/**
 * @param {string} expression
 * @return {string}
 */
export var fractionAddition = function (expression) {
  const nums = [] // 分子
  const denoms = [] //分母
  let denom = 1
  const stack = []
  const stackToNum = () => {
    // console.log('stack', stack)
    let res = ''
    let sign = false
    while (stack.length) {
      const num = stack.pop()
      if (num === '-') {
        sign = true
        continue
      } else if (num === '+') continue
      res += String(res.length ? res.length * 10 * num : num)
    }
    // console.log('res', res)
    return sign ? -Number(res) : Number(res)
  }

  const setDenom = () => {
    const currDenom = stackToNum()
    denoms.push(currDenom)
    denom = lcm(denom, currDenom)
  }

  // 取出分子分母
  for (let i = 0; i < expression.length; i++) {
    if (expression[i] === '+' || expression[i] === '-') {
      if (stack.length > 0) setDenom()
      stack.push(expression[i])
    } else if (expression[i] === '/') {
      nums.push(stackToNum())
    } else {
      stack.push(Number(expression[i]))
    }
  }
  if (stack.length > 0) setDenom()

  let num = 0
  for (let i = 0; i < nums.length; i++) {
    num += nums[i] * (denom / denoms[i])
  }

  let cd = gcd(num, denom)

  return `${num / cd}/${denom / cd}`
}

// 最大公约数
function gcd(a, b) {
  a = Math.abs(a)
  b = Math.abs(b)
  if (a < b) [a, b] = [b, a]
  if (b === 0) return a
  while (b) {
    ;[a, b] = [b, a % b]
  }
  return a
}

// 最小公倍数
function lcm(a, b) {
  return (a * b) / gcd(a, b)
}
